package com.shanzmoo.db.code;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.shanzmoo.base.util.ScannerUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 代码生成管理
 *
 * @author： Gzhao 2021/1/31
 */
@Slf4j
public class CodeGeneratorManage {

    /**
     * 数据库地址
     */
    private static final String datasourceUrl = "jdbc:mysql://rm-bp1489b4d66p01h50io.mysql.rds.aliyuncs.com:3306/jiaxin_mall_test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true";
    private static final String datasourceUsername = "jiaxin_mall_test";
    private static final String datasourcePassword = "jiaxin_mall_test@123";
    private static final String datasourceDriverName = "com.mysql.cj.jdbc.Driver";

    public static void generator(String author, String[] tableNames) {
        String moduleName = ScannerUtils.scanner("模块名");
        generator(author, moduleName, tableNames);
    }

    /**
     * 代码生成
     *
     * @param author
     * @param moduleName
     * @param tableNames
     */
    public static void generator(String author, String moduleName, String[] tableNames) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir") + "/shanzmoo-db";
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(author);
        gc.setOpen(false);
        // XML ResultMap
        gc.setBaseResultMap(true);
        // XML columList
        gc.setBaseColumnList(true);
        //覆盖原文件
        gc.setFileOverride(true);
        // 设置主键生成策略
        gc.setIdType(IdType.AUTO);
        // 设置实体对象名
        gc.setEntityName("%sEntity");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(datasourceUrl);
        dsc.setDriverName(datasourceDriverName);
        dsc.setUsername(datasourceUsername);
        dsc.setPassword(datasourcePassword);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(moduleName);

        String packageParent = "com.shanzmoo.db";


        pc.setParent(packageParent);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();

        String xmlTemplatePath = "/templates/mapper.xml.ftl";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(xmlTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName().replace("Entity", "") + "Mapper" + StringPool.DOT_XML;
            }
        });

        String mapperTemplatePath = "/templates/mapper.java.ftl";
        focList.add(new FileOutConfig(mapperTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/java/com/shanzmoo/db/" + pc.getModuleName() + "/mapper/"
                        + tableInfo.getMapperName() + StringPool.DOT_JAVA;
            }
        });

        String controllerTemplatePath = "/templates/controller.java.ftl";
        focList.add(new FileOutConfig(controllerTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return System.getProperty("user.dir") + "/shanzmoo-api/admin-api/src/main/java/com/shanzmoo/admin/web/"
                        + moduleName + "/" + tableInfo.getControllerName() + StringPool.DOT_JAVA;
            }
        });

        String managerTemplatePath = "/templates/manager.java.ftl";
        focList.add(new FileOutConfig(managerTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return System.getProperty("user.dir") + "/shanzmoo-api/admin-api/src/main/java/com/shanzmoo/admin/manager/"
                        + moduleName + "/" + tableInfo.getControllerName().replace("Controller", "Manager")
                        + StringPool.DOT_JAVA;
            }
        });

        String serviceTemplatePath = "/templates/service.java.ftl";
        focList.add(new FileOutConfig(serviceTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/java/com/shanzmoo/db/" + pc.getModuleName() + "/service/"
                        + tableInfo.getServiceName() + StringPool.DOT_JAVA;
            }
        });

        String serviceImplTemplatePath = "/templates/serviceImpl.java.ftl";
        focList.add(new FileOutConfig(serviceImplTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/java/com/shanzmoo/db/" + pc.getModuleName() + "/service/impl/"
                        + tableInfo.getServiceImplName() + StringPool.DOT_JAVA;
            }
        });

        String voTemplatePath = "/templates/vo.java.ftl";
        focList.add(new FileOutConfig(voTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/java/com/shanzmoo/db/" + pc.getModuleName() + "/entity/vo/"
                        + tableInfo.getEntityName().replace("Entity", "VO") + StringPool.DOT_JAVA;

            }
        });

        String queryTemplatePath = "/templates/query.java.ftl";
        focList.add(new FileOutConfig(queryTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/java/com/shanzmoo/db/" + pc.getModuleName() + "/entity/query/"
                        + tableInfo.getEntityName().replace("Entity", "Query") + StringPool.DOT_JAVA;
            }
        });

        String saveDtoTemplatePath = "/templates/saveDto.java.ftl";
        focList.add(new FileOutConfig(saveDtoTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return System.getProperty("user.dir") + "/shanzmoo-api/admin-api/src/main/java/com/shanzmoo/admin/domain/dto/"
                        + tableInfo.getEntityName().replace("Entity", "SaveDTO")  + StringPool.DOT_JAVA;
            }
        });

        String updateDtoTemplatePath = "/templates/updateDto.java.ftl";
        focList.add(new FileOutConfig(updateDtoTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return System.getProperty("user.dir") + "/shanzmoo-api/admin-api/src/main/java/com/shanzmoo/admin/domain/dto/"
                        + tableInfo.getEntityName().replace("Entity", "UpdateDTO")  + StringPool.DOT_JAVA;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        templateConfig.setXml(null);
        templateConfig.setMapper(null);
        templateConfig.setService(null);
        templateConfig.setServiceImpl(null);
        templateConfig.setController(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);

        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);

        strategy.setInclude(tableNames);
        strategy.setControllerMappingHyphenStyle(true);
        // 此处可以修改表前缀
        // String prefix = pc.getModuleName() + "_";
        strategy.setTablePrefix();
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();

    }


}
